package com.ruoyi.project.wechatprogram.weekend.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.shiro.service.PasswordService;
import com.ruoyi.project.system.config.service.IConfigService;
import com.ruoyi.project.wechatprogram.menu.domain.WxMenu;
import com.ruoyi.project.wechatprogram.menu.service.IWxMenuService;
import com.ruoyi.project.wechatprogram.ordermaster.domain.WxOrderMaster;
import com.ruoyi.project.wechatprogram.ordermaster.service.IWxOrderMasterService;
import com.ruoyi.project.wechatprogram.wxcategory.domain.VO.WxCategoryVO;
import com.ruoyi.project.wechatprogram.wxcategory.domain.WxCategory;
import com.ruoyi.project.wechatprogram.wxcategory.service.IWxCategoryService;
import com.ruoyi.project.wechatprogram.wxuser.domain.WxUser;
import com.ruoyi.project.wechatprogram.wxuser.service.IWxUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.wechatprogram.weekend.domain.WxWeekend;
import com.ruoyi.project.wechatprogram.weekend.service.IWxWeekendService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 餐品周期菜单Controller
 *
 * @author csx
 * @date 2020-04-08
 */
@Controller
@RequestMapping("/wechatprogram/weekend")
public class WxWeekendController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(WxWeekendController.class);

    private String prefix = "wechatprogram/weekend";

    @Autowired
    private IWxWeekendService wxWeekendService;

    @Autowired
    private IWxCategoryService wxCategoryService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private IWxMenuService wxMenuService;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IWxOrderMasterService wxOrderMasterService;


    @RequiresPermissions("wechatprogram:weekend:view")
    @GetMapping()
    public String weekend() {
        return prefix + "/weekend";
    }

    /**
     * 查询餐品周期菜单列表
     */
    @RequiresPermissions("wechatprogram:weekend:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WxWeekend wxWeekend) {
        startPage();
        List<WxWeekend> wxWeekends = wxWeekendService.selectWxWeekendList(wxWeekend);
        return getDataTable(wxWeekends);
    }

    public boolean verifyPassword(String phone, String password) {
        String initial = "123456";
        String base64 = passwordService.encryptPassword(phone, initial, "");
        if (base64.equals(password)) {
            return true;
        }
        return false;
    }

    /**
     * 小程序查询菜单列列表
     */
    @PostMapping("/wxlist")
    @ResponseBody
    public AjaxResult wxlist(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Integer weekendIndex = Integer.parseInt(request.getParameter("weekendIndex"));
        String day = request.getParameter("day");
        String iphone = request.getParameter("iphone");
        WxUser user = new WxUser();
        user.setIphone(iphone);
        user = wxUserService.selectWxUserByUser(user);
        if (verifyPassword(iphone, user.getPassword())) {
            map.put("isModPassWord", 1);
            map.put("configKey", 1);
            return AjaxResult.success(map);
        }
        // 餐品种类
        WxWeekend weekendFood = new WxWeekend();
        weekendFood.setWeekendId(weekendIndex + 1);
        List<WxWeekend> weekendList = new ArrayList<>();
        // 获取当前是周几
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        // 若当前为周日，则重新赋值
        if (w == 0) {
            w = 7;
        }
        // 判断选择的是否是当天的，若是当天的则展示当天就餐的餐品，若不是则展示点餐的餐品
        if (weekendIndex.equals(w - 1)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            weekendFood.setDay(dateFormat.format(new Date()));
            weekendList = wxWeekendService.selectWxWeekendListByToday(weekendFood);
            for (WxWeekend weekend : weekendList) {
                weekend.setMenuPictureUrl(weekend.getMenuPictureUrl());
            }
        } else {
            weekendList = wxWeekendService.selectWxWeekendList(weekendFood);
            //获取服务器域名
            String serverUrl = ServerConfig.getDomain(request);
            for (WxWeekend weekend : weekendList) {
                weekend.setMenuPictureUrl(serverUrl + weekend.getMenuPictureUrl());
            }
        }
        // 餐品类型
        WxCategory wxCategory = new WxCategory();
        wxCategory.setCategoryStatus(WxCategory.CATEGORY_STATUS_SHOW);
        List<WxCategory> wxCategoryList = wxCategoryService.selectWxCategoryList(wxCategory);

        WxCategoryVO wxCategoryVO = null;
        List<WxWeekend> cateweekList = null;
        // 将餐品封装成VO，将菜品和类目一一对应
        List<WxCategoryVO> wxCategoryVOList = new ArrayList<>();

        for (int i = 0; i < wxCategoryList.size(); i++) {
            wxCategoryVO = new WxCategoryVO();
            cateweekList = new ArrayList<>();
            for (int j = 0; j < weekendList.size(); j++) {
                if (wxCategoryList.get(i).getCategoryName().equals(weekendList.get(j).getCategoryName())) {
                    cateweekList.add(weekendList.get(j));
                }
            }
            wxCategoryVO.setCategoryName(wxCategoryList.get(i).getCategoryName());
            wxCategoryVO.setCategoryType(wxCategoryList.get(i).getCategoryType());
            wxCategoryVO.setStartTime(wxCategoryList.get(i).getStarttime().substring(0, 5));
            wxCategoryVO.setEndTime(wxCategoryList.get(i).getEndtime().substring(0, 5));
            wxCategoryVO.setWxWeekendList(cateweekList);

            //查询订单是否重复
            WxOrderMaster wxOrder = new WxOrderMaster();
            wxOrder.setDay(day);
            wxOrder.setBuyerPhone(iphone);
            wxOrder.setCategoryType(wxCategoryList.get(i).getCategoryType());
            wxOrder.setOrderStatus(WxOrderMaster.ORDER_STATUS_WAIT);
            wxOrder.setPayStatus(WxOrderMaster.PAY_STATUS_YES);
            WxOrderMaster order = wxOrderMasterService.selectWxOrderMasterOrderIsRepeat(wxOrder);
            if (!StrUtil.isBlankIfStr(order)) {
                wxCategoryVO.setIsPayStatus(1);
            }
            wxCategoryVOList.add(wxCategoryVO);
        }
        // 封装参数配置项
        String configKey = configService.selectConfigByKey("wx.menu.conf.mode");
        map.put("wxCategoryList", wxCategoryVOList);
        map.put("configKey", configKey);
        return AjaxResult.success(map);
    }

    /**
     * 导出餐品周期菜单列表
     */
    @RequiresPermissions("wechatprogram:weekend:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WxWeekend wxWeekend) {
        List<WxWeekend> list = wxWeekendService.selectWxWeekendList(wxWeekend);
        ExcelUtil<WxWeekend> util = new ExcelUtil<WxWeekend>(WxWeekend.class);
        return util.exportExcel(list, "weekend");
    }

    /**
     * 新增餐品周期菜单
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        // 初始化每日菜单添加页面回显已添加的菜品和下拉数据
        // 第一步，查找早餐主键
        WxCategory wxCategory = new WxCategory();
        wxCategory.setCategoryType(1);
        List<WxCategory> wxCategoryList = wxCategoryService.selectWxCategoryList(wxCategory);
        // 查询所有的早餐
        List<WxMenu> list = wxMenuService.selectWxMenuListByCategoryId(wxCategoryList.get(0).getId());
        // 第二步，查询周一已绑定的早餐
        WxWeekend weekend = new WxWeekend();
        weekend.setWeekendId(1);
        weekend.setCategoryId(wxCategoryList.get(0).getId());
        List<WxWeekend> weekendList = wxWeekendService.selectWxWeekendList(weekend);
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < weekendList.size(); j++) {
                if (list.get(i).getId().equals(weekendList.get(j).getMenuId())) {
                    list.get(i).setFlag(true);
                    break;
                } else {
                    list.get(i).setFlag(false);
                }
            }
        }
        mmap.put("post3", list);
        return prefix + "/add";
    }

    /**
     * 新增保存餐品周期菜单
     */
    @RequiresPermissions("wechatprogram:weekend:add")
    @Log(title = "餐品周期菜单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Integer weekIds, String weekendName, Integer categoryIds, String menuIds) {


        // 判空
        if (StrUtil.isEmpty(weekendName) || weekIds == null) {
            log.debug("每日菜单添加日期为空！");
            return AjaxResult.error("日期为空！");
        }
        if (categoryIds == null) {
            log.debug("每日菜单添加类目为空！");
            return AjaxResult.error("类目为空！");
        }
        if (StrUtil.isEmpty(menuIds)) {
            log.debug("每日菜单添加菜品为空！");
            return AjaxResult.error("菜品为空！");
        }
        AjaxResult ajaxResult = wxWeekendService.saveWeekend(weekIds, weekendName, categoryIds, menuIds);

        return ajaxResult;
    }

    /**
     * 修改餐品周期菜单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        WxWeekend wxWeekend = wxWeekendService.selectWxWeekendById(id);
        mmap.put("wxWeekend", wxWeekend);
        return prefix + "/edit";
    }

    /**
     * 修改保存餐品周期菜单
     */
    @RequiresPermissions("wechatprogram:weekend:edit")
    @Log(title = "餐品周期菜单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WxWeekend wxWeekend) {
        return toAjax(wxWeekendService.updateWxWeekend(wxWeekend));
    }

    /**
     * 删除餐品周期菜单
     */
    @RequiresPermissions("wechatprogram:weekend:remove")
    @Log(title = "餐品周期菜单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(wxWeekendService.deleteWxWeekendByIds(ids));
    }
}
